import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AliyunOssOutputUrl, tuikeSystemUrl} from '../../../../config/api';
import {PromoteService} from '../promote.service';
import {NzMessageService} from 'ng-zorro-antd';
import {
  FormBuilder,
  FormGroup,
  FormControl,
  Validators
} from '@angular/forms';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss'],
  providers: [PromoteService]
})
export class DetailComponent implements OnInit {
  validateForm: FormGroup;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  goodsModalVisible = false;
  pickType = 'goods';
  checkedInfo;
  data = [];
  flag = true;
  first_category_name;
  second_category_name;
  id;
  isEditing = false;
  keywordList = [];
  short_name_arr = [];
  num = 0;
  canEdit = false;

  activityTypeOptions = [
    { value: 0, label: '普通活动' },
    // { value: 1, label: '浪花活动' },
    // { value: 2, label: '免费试用' },
    // { value: 3, label: '领券中心' },
    // { value: 4, label: '浪花社区' },
    { value: 5, label: '秒杀活动' }
  ];

  constructor(private fb: FormBuilder,
              private promoteService: PromoteService,
              private _message: NzMessageService,
              private route: ActivatedRoute,
              private router: Router
  ) {
  }

  ngOnInit() {
    this.getPromoteDetail();
    this.validateForm = this.fb.group({
      task_name: ['', [Validators.required]],
      type: [1, [Validators.required]],
      point: ['', [Validators.required]],
      max_completion_times: ['', [Validators.required]],
      activity_type: [0],
      validity_start: ['', [Validators.required]],
      validity_end: ['', [Validators.required]],
      task_content_type: ['', [Validators.required]],
      category_name: ['', [Validators.required]],
    });
  }

  //获取关键词列表
  getKeywordList() {
    this.promoteService.getKeywordList(1).subscribe(res => {
      if (res.code === 2000) {
        this.keywordList = res.data;
      }
    })
  }

  checkTag(item) {
    if (item.checked) {
      item.checked = !item.checked;
      if (this.short_name_arr.length > 0) {
        this.short_name_arr.forEach((e, i) => {
          if (e.id == item.id) {
            this.short_name_arr.splice(i, 1);
          }
        })
      } else {
        this.short_name_arr.push({id: item.id, key: item.key});
      }
      --this.num;
    } else if (!item.checked && this.num < 2) {
      item.checked = !item.checked;
      if (this.short_name_arr.length > 0) {
        let flag = false;
        this.short_name_arr.forEach((e, i) => {
          if (e.id == item.id) {
            flag = true;
          }
        });
        if (!flag) {
          this.short_name_arr.push({id: item.id, key: item.key});
        }
      } else {
        this.short_name_arr.push({id: item.id, key: item.key});
      }
      ++this.num;
    } else {
      this._message.create('error','最多选择两个关键词');
    }
    console.log(this.short_name_arr);
  }


  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  goList() {
    if (this.flag) {
      this.router.navigate(['member/promote/list']);
      this.flag = false;
    }
  }

  _refreshStatus($event) {
    this.data.forEach((val, index) => {
      val.checked = false;
    });
  }

  getPromoteDetail() {
    this.id = +this.route.snapshot.params['id'];
    this.promoteService.getTaskInfo(this.id).subscribe(res => {
      if (res.code === 2000) {
        const data = res.data;
        const start_date = Date.parse(new Date(data.validity_start) + '');
        const end_date = Date.parse(new Date(data.validity_end) + '');
        const now_date = Date.parse(new Date() + '');
        if(now_date > end_date) {
          this.canEdit = false;
        } else {
          this.canEdit = true;
        }
        let name1 = data.short_name1;
        let name2 = data.short_name2;
        this.promoteService.getKeywordList(1).subscribe(res => {
          if (res.code === 2000) {
            this.keywordList = res.data;
            if (this.keywordList.length > 0) {
              this.keywordList.forEach((e, i) => {
                if (name1 == e.key || name2 == e.key) {
                  e['checked'] = true;
                  this.short_name_arr.push({id: e.id, key: e.key});
                  ++this.num;
                }
              });
            }
          }
        });
        if (data.task_content.type === 1) {
          this.checkedInfo = JSON.parse(data.task_content.content);
        } else {
          const goodsContent = JSON.parse(data.task_content.content);
          if (goodsContent.activity_goods[0].type === 1) {
            if (goodsContent.activity_goods[0].winners_number === 0) {
              goodsContent['groupType'] = '特价团';
            } else {
              goodsContent['groupType'] = '免单团';
            }
          } else if (goodsContent.activity_goods[0].type === 2) {
            goodsContent['groupType'] = '拉新团';
          } else {
            goodsContent['groupType'] = '抽奖团';
          }
          this.checkedInfo = goodsContent;
        }

        this.validateForm.setValue({
          task_name: data.task_name,
          type: data.type,
          point: data.point,
          max_completion_times: data.max_completion_times,
          activity_type: data.activity_type,
          validity_start: data.validity_start,
          validity_end: data.validity_end,
          task_content_type: data.task_content.type,
          category_name: data.first_category_name + ' / ' + data.second_category_name
        });
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  edit() {
    if (this.validateForm.controls['task_name'].valid) {
      let data = {};
      data['id'] = this.id;
      data['task_name'] = this.validateForm.value.task_name;
      data['activity_type'] = this.validateForm.value.activity_type;
      if (this.short_name_arr.length == 2) {
        this.short_name_arr.forEach((e, i) => {
          data['short_name' + (i + 1)] = e.key;
        })
      } else if (this.short_name_arr.length == 1) {
        data['short_name1'] = this.short_name_arr[0]['key'];
        data['short_name2'] = '';
      } else {
        data['short_name1'] = '';
        data['short_name2'] = '';
      }

      this.isEditing = true;
      this.promoteService.editTaskName(data).subscribe(res => {
        if (res.code === 2000) {
          this._message.create('success', '修改成功');
          this.router.navigate(['member/promote/list']);
        } else {
          this._message.create('error', res.message);
        }
        this.isEditing = false;
      })
    }
  }
}
